package com.ship.dispatch.controller.shipReport;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.ship.common.core.base.Page;
import com.ship.common.core.domain.R;
import com.ship.common.core.exception.BusException;
import com.ship.common.core.exception.ServiceException;
import com.ship.common.core.utils.FileUtils;
import com.ship.common.core.web.domain.BaseResultCode;
import com.ship.common.core.web.domain.JsonResult;
import com.ship.common.log.annotation.Log;
import com.ship.common.log.enums.BusinessType;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.dispatch.bean.fob.SpFobFileRecord;
import com.ship.dispatch.bean.shipBusiness.SmShipReport;
import com.ship.dispatch.bean.shipBusiness.SmShipReportRecord;
import com.ship.dispatch.model.dto.shipReport.SaveShipReportDto;
import com.ship.dispatch.model.dto.shipReport.ShipReportDto;
import com.ship.dispatch.service.ExportService;
import com.ship.dispatch.service.fob.SpFobFileRecordService;
import com.ship.dispatch.service.shipBusiness.SmShipReportService;
import com.ship.dispatch.vo.shipReport.ShipReportDetailVO;
import com.ship.system.api.RemoteFileService;
import com.ship.system.api.domain.SysFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.util.*;

@RestController
@RequestMapping("/shipReport/")
@Api(value = "shipReport", tags = "船舶午报前端控制器")
public class ShipReportController {
    @Autowired
    private SmShipReportService shipReportService;
    @Autowired
    SpFobFileRecordService spFobFileRecordService;
    @Autowired
    private ExportService exportService;
    @Value("${file_server.host}")
    private String fileServerHost;
    private static final String FILE_UPLOAD_PATH = "/group1/upload";

    @Autowired
    private RemoteFileService remoteFileService;

    /**
     * 船舶午报分页
     *
     * @param shipReport
     * @return
     */
    @ApiOperation(value = "船舶午报分页")
    @PostMapping("page")
    public JsonResult<PageInfo<SmShipReport>> page(@RequestBody SmShipReport shipReport) {
//        QueryWrapper queryWrapper = new QueryWrapper();
//        if(StringUtils.isNotBlank(shipReport.getVoyageNumber())){
//            queryWrapper.like("voyage_number",shipReport.getVoyageNumber());
//        }
//        if(StringUtils.isNotBlank(shipReport.getVesselName())){
//            queryWrapper.like("vessel_name",shipReport.getVesselName());
//        }
//        if(StringUtils.isNotBlank(shipReport.getImo())){
//            queryWrapper.like("imo",shipReport.getImo());
//        }
//        if(null != shipReport.getShipReportDate()){
//            queryWrapper.eq("ship_report_date",shipReport.getShipReportDate());
//        }
        PageInfo<SmShipReport> pageInfo = shipReportService.queryShipReportList(shipReport);
        return JsonResult.success(pageInfo);
    }

    /**
     * 上传船舶午报
     *
     * @param file
     * @return
     */
    @ApiOperation(value = "上传船舶午报")
    @PostMapping("uploadShipReport")
    @Log(title = "上传船舶午报", businessType = BusinessType.IMPORT)
    public JsonResult uploadShipReport(@RequestParam("file") MultipartFile file) {
        FileUtils.checkFileName(file);
        try {
            R<SysFile> result = remoteFileService.upload(file);
            if(result.getCode() != R.SUCCESS){
                throw new BusException("文件服务器连接失败", BaseResultCode.GENERAL_ERROR);
            }
            SpFobFileRecord spFobFileRecord = new SpFobFileRecord();
            spFobFileRecord.setPath(result.getData().getHttpsUrl());
            spFobFileRecord.setHttpPath(result.getData().getHttpUrl());
            spFobFileRecord.setName(file.getName());
            spFobFileRecord.setFileType("船舶午报");
            spFobFileRecord.setCreateDate(new Date());
            spFobFileRecord.setCreateBy(SecurityUtils.getStringUserId());
            spFobFileRecordService.save(spFobFileRecord);
            return JsonResult.success(spFobFileRecord.getId().toString());
        } catch (Exception e) {
            return JsonResult.failed("上传失败，原因：" + e.getMessage());
        }
    }

//    /**
//     * 上传附件M
//     *
//     * @return
//     */
//    public String upload(InputStream inputStream, String name) {
//        String result = "";
//        try {
//            InputStreamResource isr = new InputStreamResource(inputStream,
//                    name);
//
//            Map<String, Object> params = new HashMap<>();
//            params.put("file", isr);
//            //params.put("path", "86501729");
//            params.put("output", "json");
//            /*params.put("auth_token", "123");*/
//            String resp = HttpRequest.post(fileServerHost + FILE_UPLOAD_PATH).form(params).timeout(-1).execute().body();
//            //String resp = HttpUtil.post(fileServerHost + FILE_UPLOAD_PATH, params);
//            JSONObject re = JSONObject.parseObject(resp);
//            if (!re.getString("retcode").equals("0")) {
//                throw new BusException(re.getString("retmsg"), BaseResultCode.GENERAL_ERROR);
//            }
//            result = re.getString("domain") + re.getString("path");
//        } catch (Exception e) {
//            throw new BusException("文件服务器连接失败", BaseResultCode.GENERAL_ERROR);
//        }
//        return result;
//    }

    /**
     * 新增船舶午报
     *
     * @param shipReportDto
     * @return
     */
    @ApiOperation(value = "新增船舶午报")
    @PostMapping("saveShipReport")
    @Log(title = "新增船舶午报", businessType = BusinessType.INSERT)
    public JsonResult saveShipReport(@RequestBody SaveShipReportDto shipReportDto) throws ParseException {
        if (null != shipReportDto.getIds() && shipReportDto.getIds().size() > 0) {
            List<SpFobFileRecord> fileRecords = spFobFileRecordService.listByIds(shipReportDto.getIds());
            if (CollectionUtil.isNotEmpty(fileRecords)){
                shipReportService.saveShipReport(fileRecords);
            }else {
                throw new ServiceException("附件未上传成功，请重试", BaseResultCode.GENERAL_ERROR.getCode());
            }
//            if (null != fileRecords && fileRecords.size() > 0) {
//                fileRecords.stream().forEach(f -> {
//                    try {
//                        shipReportService.saveShipReport(f);
//                    } catch (ParseException e) {
//                        throw new RuntimeException(e);
//                    }
//                });
//            }
            return JsonResult.success();
        } else {
            return JsonResult.failed("无附件，请核实");
        }
    }

    /**
     * 修改船舶午报
     *
     * @param shipReportDto
     * @return
     */
    @ApiOperation(value = "修改船舶午报")
    @PostMapping("updateShipReport")
    @Log(title = "修改船舶午报", businessType = BusinessType.UPDATE)
    public JsonResult updateShipReport(@RequestBody ShipReportDto shipReportDto) {
        SmShipReport shipReport = shipReportService.updateShipReport(shipReportDto, spFobFileRecordService);
        return JsonResult.success(shipReport);
    }

    /**
     * 删除船舶午报
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "删除船舶午报")
    @DeleteMapping("removeShipReport/{id}")
    @Log(title = "删除船舶午报", businessType = BusinessType.DELETE)
    public JsonResult removeShipReport(@PathVariable(value = "id") Long id) {
        SmShipReport shipReport = shipReportService.removeShipReport(id, spFobFileRecordService);
        return JsonResult.success();
    }

    /**
     * 查看船舶报文
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "查看船舶报文")
    @GetMapping("getShipReportDetail/{id}")
    public JsonResult getShipReportDetail(@PathVariable(value = "id") Long id) {
        List<ShipReportDetailVO> shipReportDetailVOS = shipReportService.getShipReportDetail(id);
        return JsonResult.success(shipReportDetailVOS);
    }

    /**
     * 查询船舶午报动态
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "查询船舶午报动态")
    @GetMapping("getShipReportRecord/{id}")
    public JsonResult getShipReportRecord(@PathVariable(value = "id") Long id) {
        List<SmShipReportRecord> reportRecords = shipReportService.getShipReportRecord(id);
        return JsonResult.success(reportRecords);
    }

    /**
     * 删除附件
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "删除船舶午报附件")
    @DeleteMapping("/deleteFile/{id}")
    @Log(title = "删除船舶午报附件", businessType = BusinessType.DELETE)
    public JsonResult deleteFile(@PathVariable("id") Long id) {
        spFobFileRecordService.removeById(id);
        return JsonResult.success();
    }


    /**
     * 船舶午报数据导出
     *
     * @return
     */
    @ApiOperation(value = "船舶午报数据导出")
    @PostMapping("/page/export")
    @Log(title = "船舶午报数据导出", businessType = BusinessType.EXPORT)
    public JsonResult getShipReportExport(@RequestBody SmShipReport shipReport) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        if (shipReport.getIds() != null && shipReport.getIds().size() > 0) {

            queryWrapper.in("id", shipReport.getIds());
        }
        List<SmShipReport> exportList = shipReportService.pageExportList(shipReport, queryWrapper, new LinkedList<>());
        Field[] fields = SmShipReport.class.getDeclaredFields();
        String url = exportService.pageExport(exportList, fields, exportService.listStrByModuleAndUser
                ("sm_ship_report", SecurityUtils.getUserId()), "船舶午报信息");
        return JsonResult.success(url);
    }

    @ApiOperation("分页查询船舶午报-船舶纬度列表")
    @PostMapping("ship/page")
    public JsonResult queryShipPage(@RequestBody SmShipReport shipReport){
        PageInfo<SmShipReport> pageInfo = shipReportService.queryShipPage(shipReport);
        return JsonResult.success(pageInfo);
    }

    @ApiOperation("导出船舶午报-船舶纬度列表")
    @PostMapping("export/shipReport")
    public JsonResult exportShipReport(@RequestBody SmShipReport shipReport){
        List<SmShipReport> reportList = shipReportService.exportShipReport(shipReport);
        List<String> tableList = new ArrayList<>();
        tableList.add("vesselName");
        tableList.add("shipReportDate");
        tableList.add("shipReportLt");
        tableList.add("shipReportUtc");
        tableList.add("positionLat");
        tableList.add("positionLong");
        tableList.add("updateDate");
        tableList.add("createBy");
        List<String> tableNameList = new ArrayList<>();
        tableNameList.add("Vessel name");
        tableNameList.add("Date");
        tableNameList.add("LT");
        tableNameList.add("UTC");
        tableNameList.add("Position LAT");
        tableNameList.add("Position LONG");
        tableNameList.add("更新时间");
        tableNameList.add("操作人");
        Field[] fields = SmShipReport.class.getDeclaredFields();
        String url = exportService.exportUtil(reportList, fields, tableList,tableNameList, "船舶午报(船舶纬度)信息");
        return JsonResult.success(url);
    }

}
